   package com.sport.controller;

   import cn.dev33.satoken.annotation.SaCheckRole;
   import cn.dev33.satoken.annotation.SaMode;
   import cn.dev33.satoken.stp.StpUtil;
   import cn.hutool.core.util.RandomUtil;
   import cn.hutool.core.util.StrUtil;
   import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
   import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
   import com.github.xiaoymin.knife4j.annotations.ApiSupport;
   import com.sport.entity.SysUser;
   import com.sport.entity.dto.Option;
   import com.sport.model.PageParams;
   import com.sport.model.Result;
   import com.sport.service.SysUserService;
   import com.sport.utils.PasswordUtils;
   import io.swagger.v3.oas.annotations.Operation;
   import io.swagger.v3.oas.annotations.Parameter;
   import io.swagger.v3.oas.annotations.enums.ParameterIn;
   import io.swagger.v3.oas.annotations.tags.Tag;
   import jakarta.annotation.Resource;
   import org.springframework.web.bind.annotation.*;
   import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

   import java.util.List;
   import java.util.Map;
   import java.util.Objects;

   @RestController
   @Tag(name = "用户管理")
   @RequestMapping("/sysUser")
   @ApiSupport(author = "开心摆烂", order = 2)
   public class SysUserController {

       @Resource
       private SysUserService userService;

       // 根据id查询
       @GetMapping("Info/{id}")
       @Operation(summary = "根据id查询", parameters = {
               @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
       })
       @ApiOperationSupport(order = 1)
       public Result<SysUser> getById(@PathVariable String id) {
           return Result.success(userService.getById(id));
       }

       // 列表查询
       @PostMapping("/page")
       @Operation(summary = "列表查询")
       @ApiOperationSupport(order = 2)
       public Result<Page<SysUser>> pageQuery(@RequestBody PageParams<SysUser> pageParams) {
           SysUser params = pageParams.getParams();
           LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
           lqw.like(StrUtil.isNotBlank(params.getUsername()), SysUser::getUsername, params.getUsername());
           lqw.like(StrUtil.isNotBlank(params.getNickname()), SysUser::getNickname, params.getNickname());
           Page<SysUser> page = userService.page(pageParams.getPage(), lqw);
           page.getRecords().forEach(item -> item.setRoles(userService.getRoles(item.getId())));
           return Result.success(page);
       }

       // 分页查询,
       @PostMapping("/list")
       @Operation(summary = "分页查询")
       @ApiOperationSupport(order = 3)
       public Result<List<SysUser>> pageQuery(@RequestBody SysUser user) {
           LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
           lqw.like(StrUtil.isNotBlank(user.getUsername()), SysUser::getUsername, user.getUsername());
           lqw.eq(user.getSex() != null, SysUser::getSex, user.getSex());
           return Result.success(userService.list(lqw));
       }

       // 新增
       @PostMapping("/insert")
       @Operation(summary = "新增")
       @ApiOperationSupport(order = 4)
       public Result<Boolean> insert(@RequestBody SysUser sysUser) {
           //添加用户，并对其加密
           String slat = RandomUtil.randomString(16);
           sysUser.setSlat(slat);
           String password = sysUser.getPassword();
           String encrypt = PasswordUtils.encrypt(slat, password);
           sysUser.setPassword(encrypt);
           if (userService.save(sysUser)) {
               List<Option> roles = sysUser.getRoles();
               if (roles.size() > 0) {
                   List<String> roleIds = roles.stream().map(Option::getValue).toList();
                   userService.insertRole(sysUser.getId(), roleIds);

               }
               return Result.success("新增成功");
           }
           return Result.error("新增失败");
       }

       //更新
       @PutMapping("/update")
       @Operation(summary = "更新")
       @ApiOperationSupport(order = 5)
       public Result<Boolean> update(@RequestBody SysUser sysUser) {
           if (sysUser.getRoles() != null) {
               userService.deleteRole(sysUser.getId());
           }
           sysUser.setPassword(null);
           if (userService.updateById(sysUser)) {
               if (sysUser.getRoles() != null) {
                   List<Option> roles = sysUser.getRoles();
                   if (roles.size() > 0) {
                       List<String> roleIds = roles.stream().map(Option::getValue).toList();
                       userService.insertRole(sysUser.getId(), roleIds);
                   }
               }
               return Result.success("更新成功");
           } else {
               return Result.error("更新失败");
           }
       }

       //删除
       @DeleteMapping("/delete/{id}")
       @Operation(summary = "删除", parameters = {
               @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
       })
       @ApiOperationSupport(order = 6)
       public Result<Boolean> deleteById(@PathVariable String id) {
           if (userService.removeById(id)) {
               return Result.success("删除成功");
           } else {
               return Result.error("删除失败");
           }
       }

       //踢人下线
       @PostMapping("/kickUserOut")
       @SaCheckRole(value = {"admin"}, mode = SaMode.OR)
       @ApiOperationSupport(order = 7)
       @Operation(summary = "踢人下线", description = "根据用户ID踢人下线")
       public Result<Boolean> kickUserOut(@RequestParam String id) {
           try {
               // 获取用户的所有 token
               List<String> tokens = StpUtil.getTokenValueListByLoginId(id);
               if (tokens == null || tokens.isEmpty()) {
                   return Result.success("用户未登录");
               }
               for (String token : tokens) {
                   // 删除指定 token
                   StpUtil.kickoutByTokenValue(token);
               }
               return Result.success("用户已下线");
           } catch (Exception e) {
               return Result.error("踢人下线失败: " + e.getMessage());
           }
       }

       //重置用户密码
        @PostMapping("/resetPassword")
        @SaCheckRole(value = {"admin"}, mode = SaMode.OR)
        @Operation(summary = "重置用户密码", description = "根据用户ID重置用户密码")
        @ApiOperationSupport(order = 8)
        public Result<Boolean> resetPassword(@RequestParam Long id) {
            SysUser user = userService.getById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }

            String password = "123456"; // 默认密码
            String slat = RandomUtil.randomString(16);
            user.setSlat(slat);
            String encrypt = PasswordUtils.encrypt(slat, password);
            user.setPassword(encrypt);

            if (userService.updateById(user)) {
                return Result.success("密码重置成功");
            } else {
                return Result.error("密码重置失败");
            }
        }

       //修改密码
       @PutMapping("/changePassword")
       @Operation(summary = "修改密码", description = "用户修改自己的密码")
       @ApiOperationSupport(order = 9)
       public Result<Boolean> changePassword(@RequestBody Map<String, String> passwordMap) {
           String oldPassword = passwordMap.get("oldPassword");
           String newPassword = passwordMap.get("newPassword");

           if (oldPassword == null || newPassword == null) {
               return Result.error("旧密码或新密码不能为空");
           }

           // 获取当前登录用户的ID
           String userId = StpUtil.getLoginIdAsString();
           SysUser user = userService.getById(userId);
           if (user == null) {
               return Result.error("用户不存在");
           }

           // 验证旧密码是否正确
           String salt = user.getSlat();
           String encryptedOldPassword = PasswordUtils.encrypt(salt, oldPassword);
           if (!Objects.equals(user.getPassword(), encryptedOldPassword)) {
               return Result.error("旧密码不正确");
           }

           // 加密新密码
           String newSalt = RandomUtil.randomString(16);
           String encryptedNewPassword = PasswordUtils.encrypt(newSalt, newPassword);

           // 更新用户密码和盐
           user.setPassword(encryptedNewPassword);
           user.setSlat(newSalt);
           if (userService.updateById(user)) {
               return Result.success("密码修改成功");
           } else {
               return Result.error("密码修改失败");
           }
       }



   }

   